package com.hancher.plugins.hrnumberaddsub;

import java.math.BigDecimal;

public class HrNumberAddSubUtil {
    public static BigDecimal subNum(String numStr, BigDecimal addNum, BigDecimal maxNum, BigDecimal minNum, int scale) {
        BigDecimal num = null;
        if (numStr == null || numStr.isEmpty()) {
            num = BigDecimal.ZERO;
        } else {
            try {
                num = new BigDecimal(numStr);
            } catch (Exception e) {
                num = BigDecimal.ZERO;
            }
        }
        num = num.subtract(addNum);
        return modifyNum(num, maxNum, minNum, scale);
    }
    public static BigDecimal subNum(BigDecimal num1, BigDecimal addNum, BigDecimal maxNum, BigDecimal minNum, int scale) {
        BigDecimal num = num1 == null? BigDecimal.ZERO : num1;
        num = num.subtract(addNum);
        return modifyNum(num, maxNum, minNum, scale);
    }
    public static BigDecimal subNum(Double num1, BigDecimal addNum, BigDecimal maxNum, BigDecimal minNum, int scale) {
        BigDecimal num = num1 == null? BigDecimal.ZERO : BigDecimal.valueOf(num1);
        num = num.subtract(addNum);
        return modifyNum(num, maxNum, minNum, scale);
    }

    public static BigDecimal addNum(String numStr, BigDecimal addNum, BigDecimal maxNum, BigDecimal minNum, int scale) {
        BigDecimal num = null;
        if (numStr == null || numStr.isEmpty()) {
            num = BigDecimal.ZERO;
        } else {
            try {
                num = new BigDecimal(numStr);
            } catch (Exception e) {
                num = BigDecimal.ZERO;
            }
        }
        num = num.add(addNum);
        return modifyNum(num, maxNum, minNum, scale);
    }

    public static BigDecimal addNum(BigDecimal num1, BigDecimal addNum, BigDecimal maxNum, BigDecimal minNum, int scale) {
        BigDecimal num = num1 == null? BigDecimal.ZERO : num1;
        num = num.add(addNum);
        return modifyNum(num, maxNum, minNum, scale);
    }
    public static BigDecimal addNum(Double num1, BigDecimal addNum, BigDecimal maxNum, BigDecimal minNum, int scale) {
        BigDecimal num = num1 == null? BigDecimal.ZERO : BigDecimal.valueOf(num1);
        num = num.add(addNum);
        return modifyNum(num, maxNum, minNum, scale);
    }

    public static BigDecimal modifyNum(BigDecimal num, BigDecimal maxNum, BigDecimal minNum, int scale) {
        if (maxNum != null && num.compareTo(maxNum) > 0) {
            num = maxNum;
        } else if (minNum != null && num.compareTo(minNum) < 0) {
            num = minNum;
        }
        return num.setScale(scale, BigDecimal.ROUND_DOWN);
    }
}
